<template>
  <w-dialog type="team" :border="false" closeFree width="750px" @ok="selectOk" :title="title" v-model="visible"
            :okText="okText" :cancelText="cancelText" @cancel="cancelFn()">
    <div class="picker" v-if="chooseUser">
      <div class="candidate" v-loading="loading">
        <div v-if="type !== 'role'">
          <el-input v-model="search" @input="searchUser" style="width: 100%;" size="small"
                    clearable placeholder="搜索信息" prefix-icon="el-icon-search"/>
          <div v-show="!showUsers">
            <div style="margin-top: 5px">
              <el-checkbox v-model="checkAll" @change="handleCheckAllChange" :disabled="!multiple">全选</el-checkbox>
              <span v-show="deptStack.length > 0" class="top-dept" @click="beforeNode">上一级</span>
            </div>
          </div>
        </div>
        <div class="role-header" v-else>
          <div>系统角色</div>
        </div>
        <div class="org-items" :style="type === 'role' ? 'height: 350px':''">
          <el-empty :image-size="100" description="似乎没有数据" v-show="orgs.length === 0"/>
          <div v-for="(org, index) in orgs" :key="index" class="org-items-line org-item org-user-item"
               @click="selectChange(org)">
            <el-checkbox v-model="org.selected" :disabled="disableDept(org)"></el-checkbox>
            <div style="display: flex; align-items: center">
              <el-avatar :size="30" :src="org.avatar" v-if="$isNotEmpty(org.avatar)"/>
              <span v-else class="avatar">{{ getShortName(org.nickName) }}</span>
              <span class="name">{{ org.nickName }} {{ org.phone }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="selected selectedRight">
        <div class="count">
          <span>已选 {{ select.length }} 项</span>
          <span @click="clearSelected">清空</span>
        </div>
        <div class="org-items" style="height: 350px;">
          <el-empty :image-size="100" description="请点击左侧列表选择数据" v-show="select.length === 0"/>
          <div v-for="(org, index) in select" :key="index" class="org-item org-user-item">
            <div style="display: flex; align-items: center">
              <el-avatar :size="30" :src="org.avatar" v-if="$isNotEmpty(org.avatar)"/>
              <span v-else class="avatar">{{ getShortName(org.nickName) }}</span>
              <span class="name">{{ org.nickName }}</span>
            </div>
            <i class="el-icon-close" @click="noSelected(index)"></i>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <div>
        <el-table
          v-loading="loading"
          :data="select"
        >
          <el-table-column label="姓名" align="center" prop="nickName" width="100"/>
          <el-table-column label="手机号" align="center" prop="phone" width="110"/>
          <el-table-column label="岗位" align="center" prop="postId">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.postId"
                placeholder="请选择岗位"
                class="w100"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in postList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="职务" align="center" prop="name" width="110">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.duties"
                placeholder="请选择职务"
                class="w100"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in dict.type.sys_work_post"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="调入日期" align="center" prop="name">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.day"
                class="w100"
                value-format="yyyy-MM-dd"
                type="date"
                size="small"
                placeholder="请选择"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" prop="name" width="70">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="noSelected(scope.$index)"
              >去除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </w-dialog>
</template>

<script>
import {listPointsUserOpen} from '@/api/system/user' // 用户
import {addStagnationPointUserAll} from "@/api/system/stagnation_point";
import {listProjectPost} from "@/api/system/project";
import cache from "../../plugins/cache";

export default {
  name: "OrgPicker",
  components: {},
  dicts: ['sys_work_post'],
  props: {
    title: {
      default: '请选择',
      type: String
    },
    type: {
      default: 'org', //org选择部门/人员  user-选人  dept-选部门 role-选角色
      type: String
    },
    multiple: { //是否多选
      default: false,
      type: Boolean
    },
    selected: {
      default: () => {
        return []
      },
      type: Array
    },
    pointData: {
      default: () => {
        return {}
      },
      type: Object
    },
    isMaster: {
      default: 0,
      type: Number
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      checkAll: false,
      nowDeptId: 1,
      isIndeterminate: false,
      searchUsers: [],
      nodes: [],
      select: [],
      search: '',
      deptStack: [],
      okText: '下一步',
      cancelText: '取消', //
      chooseUser: true,
      tableType: 'org', //org选择部门/人员  user-选人  dept-选部门 role-选角色
      postList: []
    }
  },
  computed: {
    deptStackStr() {
      return String(this.deptStack.map(v => v.name)).replaceAll(',', ' > ')
    },
    orgs() {
      return !this.search || this.search.trim() === '' ? this.nodes : this.searchUsers
    },
    showUsers() {
      return this.search || this.search.trim() !== ''
    }
  },
  created() {
  },
  methods: {
    show() {
      console.log('pointData==>', this.pointData)
      this.visible = true
      this.init()
      this.getOrgList()
      // 获取项目详情岗位
      this.getPostList()
    },
    getPostList() {
      listProjectPost({
        pageNum: 1,
        pageSize: 10,
        projectId: this.pointData.projectId,
      }).then(res => {
        this.postList = res.rows
        console.log('res===>', res)
      })
    },
    orgItemClass(org) {
      return {
        'org-item': true,
        'org-dept-item': org.type === 'dept',
        'org-user-item': org.type === 'user',
        'org-role-item': org.type === 'role'
      }
    },
    disableDept(node) {
      return this.type === 'user' && 'dept' === node.type
    },
    getOrgList() {
      this.loading = true
      listPointsUserOpen({pointsId: this.pointData.id, nickName: this.search}).then(rsp => {
        this.loading = false
        let list = []
        for (let item of rsp.data) {
          list.push(
            {
              userId: item.userId,
              nickName: item.nickName,
              avatar: item.avatar,
              phone: item.phonenumber,
              duties: '1', // 职务
              isMaster: this.isMaster, // 主岗/兼岗
              day: this.formatDate(new Date()), // 日期
              projectId: this.pointData.projectId, // 项目id
              pointsId: this.pointData.id, // 执勤点id
              deptId: item.deptId, // 组织id
              postId: '' // 岗位
            }
          )
        }
        this.nodes = list
        this.selectToLeft()
      }).catch(err => {
        this.loading = false
        this.$message.error(err.response.data)
      })
    },
    formatDate(value, type) {
      // 计算日期相关值
      let time = typeof value == 'number' ? new Date(value) : value;
      let Y = time.getFullYear();
      let M = time.getMonth() + 1;
      let D = time.getDate();
      let h = time.getHours();
      let m = time.getMinutes();
      let s = time.getSeconds();
      let week = time.getDay();
      // 如果传递了type的话
      if (type == undefined) {
        return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D);
      } else if (type == 'week') {
        // 在quartz中 1为星期日
        return week + 1;
      }
    },
    getShortName(name) {
      if (name) {
        return name.length > 2 ? name.substring(1, 3) : name;
      }
      return '**'
    },
    searchUser() {
      let userName = this.search.trim()
      this.searchUsers = []
      this.loading = true
      // getUserByName({userName: userName}).then(rsp => {
      //   this.loading = false
      //   this.searchUsers = rsp.data
      //   this.selectToLeft()
      // }).catch(err => {
      //   this.loading = false
      //   this.$message.error("接口异常")
      // })
    },
    selectToLeft() {
      let nodes = this.search.trim() === '' ? this.nodes : this.searchUsers;
      nodes.forEach(node => {
        for (let i = 0; i < this.select.length; i++) {
          if (this.select[i].id === node.id) {
            node.selected = true;
            break;
          } else {
            node.selected = false;
          }
        }
      })
    },
    selectChange(node) {
      console.log('选中的信息', node)
      // 需要将信息保存进模块
      if (node.selected) {
        this.checkAll = false;
        for (let i = 0; i < this.select.length; i++) {
          if (this.select[i].id === node.id) {
            this.select.splice(i, 1);
            break;
          }
        }
        node.selected = false;
      } else if (!this.disableDept(node)) {
        node.selected = true
        let nodes = this.search.trim() === '' ? this.nodes : this.searchUsers;
        if (!this.multiple) {
          nodes.forEach(nd => {
            if (node.id !== nd.id) {
              nd.selected = false
            }
          })
        }
        if (node.type === 'dept') {
          if (!this.multiple) {
            this.select = [node]
          } else {
            this.select.unshift(node);
          }
        } else {
          if (!this.multiple) {
            this.select = [node]
          } else {
            this.select.push(node);
          }
        }
      }
    },
    noSelected(index) {
      let nodes = this.nodes;
      for (let f = 0; f < 2; f++) {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === this.select[index].id) {
            nodes[i].selected = false;
            this.checkAll = false;
            break;
          }
        }
        nodes = this.searchUsers;
      }
      this.select.splice(index, 1)
    },
    handleCheckAllChange() {
      this.nodes.forEach(node => {
        if (this.checkAll) {
          if (!node.selected && !this.disableDept(node)) {
            node.selected = true
            this.select.push(node)
          }
        } else {
          node.selected = false;
          for (let i = 0; i < this.select.length; i++) {
            if (this.select[i].id === node.id) {
              this.select.splice(i, 1);
              break;
            }
          }
        }
      })
    },
    nextNode(node) {
      if (!node.selected) {
        this.tableType = 'org' // org
        this.nowDeptId = node.id
        this.deptStack.push(node)
        this.getOrgList()
      }
    },
    beforeNode() {
      console.log('this.deptStack:', this.deptStack)
      if (this.deptStack.length === 0) {
        return;
      }
      if (this.deptStack.length < 2) {
        this.nowDeptId = 1
      } else {
        this.nowDeptId = this.deptStack[this.deptStack.length - 2].id
      }
      this.deptStack.splice(this.deptStack.length - 1, 1);
      this.getOrgList()
    },
    recover() {
      this.postList = []
      this.select = []
      this.nodes.forEach(nd => nd.selected = false)
    },
    selectOk() {
      console.log('需要把数据确认后提交出去：', this.select)
      if (!this.select.length) {
        this.$message.error('请选择需要调入人员')
        return
      }
      if (this.chooseUser) {
        this.cancelText = '再选人'
        this.okText = '确定'
        this.chooseUser = false
      } else {
        this.submitForm()
      }
      // this.$emit('ok', Object.assign([], this.select.map(v => {
      //   v.avatar = undefined
      //   return v
      // })))
      // this.visible = false
      // this.recover()
    },
    submitForm() {
      let list_ = JSON.parse(JSON.stringify(this.select))
      let that = this

      for (let item of list_) {
        delete item.avatar
        delete item.selected
        if (!item.postId) {
          this.$message.error('请选择人员岗位')
          return
        }
      }
      this.$modal.loading("正在保存中，请稍候...");
      addStagnationPointUserAll({stagnationPointUsers: list_}).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.$emit('ok')
        this.visible = false
        this.recover()
        this.cancelText = '取消'
        this.okText = '下一步'
        this.chooseUser = true
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 300)
      }).catch(() => {
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 300)
      });
    },
    cancelFn() {
      if (this.chooseUser) {
        this.visible = false
        this.close()
      } else {
        this.cancelText = '取消'
        this.okText = '下一步'
        this.chooseUser = true
      }
    },
    clearSelected() {
      this.$confirm('您确定要清空已选中的项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.recover()
      })
    },
    close() {
      this.$emit('close')
      this.recover()
    },
    init() {
      console.log('this.typegetOrgList:', this.type)
      this.checkAll = false;
      this.nowDeptId = 1;
      this.deptStack = [];
      this.nodes = []
      this.select = Object.assign([], this.selected)
      this.selectToLeft()
    }
  }
}
</script>

<style lang="less" scoped>

@containWidth: 280px;

.candidate, .selectedRight {
  //position: absolute;
  display: inline-block;
  //width: @containWidth;
  flex: 1;
  height: 400px;
  border: 1px solid #e8e8e8;
}

.picker {
  display: flex;
  height: 402px;
  //position: relative;
  text-align: left;

  .candidate {
    //left: 0;
    //top: 0;

    .role-header {
      padding: 10px !important;
      margin-bottom: 5px;
      border-bottom: 1px solid #e8e8e8;
    }

    .top-dept {
      margin-left: 20px;
      cursor: pointer;
      color: #38adff;
    }

    .next-dept {
      color: #333;
      cursor: pointer;
      font-size: 13px;
    }

    .next-deptUser {
      color: #333;
      cursor: pointer;
      font-size: 13px;
      position: absolute;
      right: 38px;
    }

    .next-dept-disable {
      color: #8c8c8c;
      cursor: not-allowed;
      font-size: 13px;
    }

    & > div:first-child {
      padding: 5px 10px;
    }

  }

  .selected {
    right: 0;
    top: 0;
  }

  .org-items {
    overflow-y: auto;
    height: 310px;

    .el-icon-close {
      position: absolute;
      right: 5px;
      cursor: pointer;
      font-size: larger;
    }

    .org-dept-item {
      padding: 10px 5px;

      & > div {
        display: inline-block;

        & > span:nth-child(3) {
          position: absolute;
          right: 5px;
        }
      }
    }

    .org-role-item {
      display: flex;
      align-items: center;
      padding: 10px 5px;
    }

    /deep/ .org-user-item {
      display: flex;
      align-items: center;
      padding: 5px;

      & > div {
        display: inline-block;
      }

      .avatar {
        width: 35px;
        text-align: center;
        line-height: 35px;
        background: #ff7f42;
        color: white;
        border-radius: 50%;
        font-size: 11px;
      }
    }

    /deep/ .org-item {
      margin: 0 5px;
      border-radius: 5px;
      position: relative;

      .el-checkbox {
        margin-right: 10px;
      }

      .name {
        margin-left: 5px;
      }

      &:hover {
        background: #f1f1f1;
      }
    }
  }
}

.selected {
  border-left: none;

  .count {
    width: 100%;
    padding: 10px;
    display: inline-block;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 5px;

    & > span:nth-child(2) {
      float: right;
      color: #c75450;
      cursor: pointer;
    }
  }
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.disabled {
  cursor: not-allowed !important;
  color: #8c8c8c !important;
}

::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #efefef;
}

.org-items-line {
  cursor: pointer;
}

.org-items-line:hover .name {
  text-decoration: underline;
}
</style>
